<template>
    <a-modal
        :title="modalTitle"
        :visible="visible"
        :footer="null"
        :mask-closable="false"
        :closable="false"
        :width="400"
        @cancel="handleCancel"
    >
        <div class="download-progress-container">
            <!-- Loading 图标 -->
            <div class="loading-container">
                <a-spin size="large" :spinning="isDownloading">
                    <a-icon slot="indicator" type="loading" style="font-size: 48px;" spin />
                </a-spin>
            </div>
            
            <!-- 状态信息 -->
            <div class="status-info">
                <p class="download-status">{{ downloadStatus }}</p>
                <p v-if="currentFile" class="current-file">正在处理: {{ currentFile }}</p>
                <p v-if="progressInfo" class="progress-info">{{ progressInfo }}</p>
            </div>
            
            <!-- 操作按钮 -->
            <div class="action-buttons">
                <a-button 
                    type="danger" 
                    :disabled="!isDownloading || isStopping"
                    :loading="isStopping"
                    @click="confirmStop"
                >
                    {{ isStopping ? '正在停止...' : '停止下载' }}
                </a-button>
            </div>
        </div>
    </a-modal>
</template>

<script>
import DeviceTabManager from '@/api/TabManager/DeviceTabManager'

export default {
    name: 'DownloadProgress',
    props: {
        visible: {
            type: Boolean,
            default: false,
            required: true
        },
        deviceUpdateMode: {
            type: String,
            default: 'ethernet'
        },
        isSerialPortOpen: {
            type: Boolean,
            default: false
        },
        networkParams: {
            type: Object,
            default: () => ({
                ipAddress: '',
                port: '8888'
            })
        }
    },
    data() {
        return {
            downloadStatus: '准备下载...',
            currentFile: '',
            progressInfo: '',
            isDownloading: false,
            isStopping: false,
            deviceTabManager: new DeviceTabManager(),
            progressTimer: null
        }
    },
    computed: {
        modalTitle() {
            return this.isDownloading ? '下载进行中' : '下载配置'
        }
    },
    watch: {
        visible(newVal) {
            if (newVal) {
                this.startDownload()
            } else {
                this.cleanup()
            }
        }
    },
    beforeDestroy() {
        this.cleanup()
    },
    methods: {
        // 开始下载流程
        async startDownload() {
            this.isDownloading = true
            this.downloadStatus = '正在初始化下载...'
            this.startProgressPolling()
            this.$emit('download-started')
            
            try {
                // 执行实际的下载逻辑
                await this.executeDownload()
            } catch (error) {
                console.error('❌ [DownloadProgress] 下载失败:', error)
                this.downloadCompleted(false, '下载失败: ' + error.message)
            }
        },
        
        // 开始轮询进度
        startProgressPolling() {
            this.progressTimer = setInterval(async() => {
                try {
                    const response = await this.deviceTabManager.getDownloadProgress()
                    if (response.code === 0) {
                        this.updateProgress(response.data)
                    }
                } catch (error) {
                    console.error('❌ [DownloadProgress] 获取下载进度失败:', error)
                }
            }, 1000) // 每秒更新一次
        },
        
        // 更新进度信息
        updateProgress(data) {
            if (data.status) {
                this.downloadStatus = data.status
            }
            if (data.currentFile) {
                this.currentFile = data.currentFile
            }
            if (data.progressInfo) {
                this.progressInfo = data.progressInfo
            }
            
            // 如果下载完成
            if (data.isCompleted) {
                this.downloadCompleted(data.success, data.message)
            }
        },
        
        // 执行下载逻辑
        async executeDownload() {
            let response
            
            if (this.deviceUpdateMode === 'serialport') {
                // 串口模式
                if (!this.isSerialPortOpen) {
                    throw new Error('串口未打开')
                }
                
                // 1. 生成文件
                this.downloadStatus = '正在生成文件...'
                this.currentFile = '配置文件'
                
                const generateResponse = await this.deviceTabManager.generateFileViaSerial()
                if (generateResponse.code !== 0) {
                    throw new Error('生成文件失败: ' + generateResponse.msg)
                }
                
                // 2. 下载配置
                this.downloadStatus = '正在下载配置...'
                this.currentFile = '设备配置'
                
                response = await this.deviceTabManager.downloadConfigViaSerial()
                
            } else {
                // 网络模式
                const params = {
                    ip: this.networkParams.ipAddress,
                    port: parseInt(this.networkParams.port)
                }
                
                // 1. 生成文件
                this.downloadStatus = '正在生成文件...'
                this.currentFile = '配置文件'
                
                const generateResponse = await this.deviceTabManager.generateFileViaNetwork(params)
                if (generateResponse.code !== 0) {
                    throw new Error('生成文件失败: ' + generateResponse.msg)
                }
                
                // 2. 下载配置
                this.downloadStatus = '正在下载配置...'
                this.currentFile = '设备配置'
                
                response = await this.deviceTabManager.downloadConfigViaNetwork(JSON.stringify(params))
            }
            
            // 检查下载结果
            if (response.code === 0) {
                this.downloadCompleted(true, '下载配置成功')
            } else {
                this.downloadCompleted(false, '下载配置失败: ' + response.msg)
            }
        },
        
        // 下载完成处理
        downloadCompleted(success, message) {
            this.cleanup()
            this.$emit('download-completed', { success, message })
            this.$emit('update:visible', false)
        },
        
        // 确认停止下载
        confirmStop() {
            this.$confirm({
                title: '确认停止下载',
                content: '确定要停止当前的下载任务吗？已下载的内容将会丢失。',
                okText: '确定停止',
                cancelText: '继续下载',
                type: 'warning',
                onOk: () => {
                    this.stopDownload()
                }
            })
        },
        
        // 停止下载
        async stopDownload() {
            try {
                this.isStopping = true
                this.downloadStatus = '正在停止下载...'
                
                const response = await this.deviceTabManager.stopDownload()
                
                if (response.code === 0) {
                    console.log('✅ [DownloadProgress] 停止下载成功')
                    this.$message.success('已停止下载')
                } else {
                    console.error('❌ [DownloadProgress] 停止下载失败:', response.msg)
                    this.$message.error('停止下载失败: ' + response.msg)
                }
            } catch (error) {
                console.error('❌ [DownloadProgress] 停止下载异常:', error)
                this.$message.error('停止下载异常: ' + error.message)
            } finally {
                // 无论成功失败，都发送停止事件并关闭对话框
                this.$emit('download-stopped')
                this.cleanup()
                this.$emit('update:visible', false)
            }
        },
        
        // 清理资源
        cleanup() {
            if (this.progressTimer) {
                clearInterval(this.progressTimer)
                this.progressTimer = null
            }
            this.isDownloading = false
            this.isStopping = false
            this.downloadStatus = '准备下载...'
            this.currentFile = ''
            this.progressInfo = ''
        },
        
        // 处理取消（实际上不允许直接取消）
        handleCancel() {
            // 不允许直接关闭，必须通过停止按钮
        }
    }
}
</script>

<style scoped>
.download-progress-container {
    text-align: center;
    padding: 30px;
}
.loading-container {
    margin-bottom: 30px;
}
.loading-container :deep(.ant-spin-dot) {
    font-size: 48px;
}
.loading-container :deep(.ant-spin-dot i) {
    width: 22px;
    height: 22px;
}
.status-info {
    margin-bottom: 30px;
}
.download-status {
    font-size: 18px;
    color: #1890ff;
    margin-bottom: 15px;
    font-weight: 500;
}
.current-file {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
    word-break: break-all;
}
.progress-info {
    font-size: 14px;
    color: #999;
    margin-bottom: 0;
}
.action-buttons {
    display: flex;
    justify-content: center;
    gap: 10px;
}
.action-buttons .ant-btn {
    min-width: 120px;
    height: 36px;
    font-size: 14px;
}
</style> 